// 申请单录入
import React from 'react';
import { Row, Col, Card, Tooltip, Icon, Input, Radio, Tree, Button, DatePicker, message, Modal } from 'antd';
import store from 'store';
import { $http } from 'containers/config/https';
import '../style/CMOrderSave.less';
import InspectionRequest from './InspectionRequest';
import { Util, dayFormat } from 'tools/index';
import ApplicationCheck from './ApplicationCheck';
import RangeDatePicker from 'components/rangePicker/index';
import moment from 'moment';

const { RangePicker } = DatePicker;
const doctorOrder = require('../image/img/icon_doctororder.png');
const { TreeNode } = Tree;
const confirm = Modal.confirm;

export default class EntryApplicationForm extends React.Component {
    constructor(props) {
        super(props);
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        var patientData = JSON.parse(sessionStorage.getItem('patientData'))
        this.state = {
            visibleCrad: true, // 是否展现科室申请模板
            showQuery: false, // 是否暂时查询列表
            radioValue: '',
            appListHeight: 0, // 本次就诊申请单列表查询模块高度
            userData: userData,
            patientData: patientData,
            radioCode: 'E',
            tabStatus: false,
            checkStatus: false,
            selectID: '',
            expandedKeys: ['1', '2'],
            defaultBtn: 3
        };
    }

    componentDidMount() {
        this.props.onRef && this.props.onRef(this)
        this.loadBasicApplication()//获取基础申请单数据
        this.loadClassIfication()//获取举出申请单分类
        this.loadDetailOfDoctor()//获取就诊申请单详情
        this.loadApplicationList()
        this.loadLocalMsg()
    }

    loadLocalMsg() {
        let data = {
            params: [{
                compontName: "ApplicationForm",
                type: "C",
                reactCode: ['ApplicationForm']
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040073",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    this.setState({
                        localeProvider: this.state.userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
                    })
                }
            }
        })
    }

    //国际化
    setMessage(name, message) {
        return this.state.localeProvider && this.state.localeProvider[name] ? this.state.localeProvider[name][message] : ''
    }

    //获取基础申请单数据
    loadBasicApplication() {
        var params = {
            params: [{
                CBid: ''
            }]
        }
        $http.post('urlDeault', this, {
            code: "03010003",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        basicData: res.data
                    })
                }
            }
        });
    }

    loadClassIfication() {
        var params = {
            params: [{
                searchCode: this.state.searchCode,
                CBid: this.state.radioValue,
                hospID: this.state.userData.hospID
            }]
        }

        $http.post('urlDeault', this, {
            code: "03010004",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    var data = res.data;
                    var CBid = '', breadcrumb = ''
                    var expandedKeys = []
                    if (!Util.isEmpty(data)) {
                        for (var i = 0; i < data.length; i++) {
                            CBid = data[0].CBid,
                                breadcrumb = data[0].breadcrumb
                            expandedKeys.push(data[i].CBid)
                        }
                    }

                    this.setState({
                        classInication: res.data,
                        CBid: CBid,
                        expandedKeys: expandedKeys,
                        breadcrumb: breadcrumb,
                    }, () => {
                        this.loadClassificationAdvice()
                    })
                }
            }
        });
    }

    //获取分类医嘱详情
    loadClassificationAdvice(code) {
        var params = {
            params: [{
                appTypeID: this.state.nodeID,
                hospID: this.state.userData.hospID,
                locID: this.state.userData.locID,
                admID: this.state.patientData.admID,
                searchCode: code,
                CBid: this.state.CBid
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050098",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        dataSource: res.result,
                        selectList: ''
                    })
                }
            }
        });
    }

    loadDetailOfDoctor() {
        var params = {
            params: [{
                admID: this.state.patientData.admID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050099",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        DetailData: res.result
                    })
                }
            }
        });
    }

    loadApplicationList() {
        var params = {
            params: [{
                admID: this.state.patientData.admID,
                hospID: this.state.userData.hospID,
                dateFrom: this.state.admDateFrom ? moment(this.state.admDateFrom).format(dayFormat) : '',
                dateTo: this.state.admDateTo ? moment(this.state.admDateTo).format(dayFormat) : '',
                searchCode: this.state.searchList
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050109",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        applicationList: res.result
                    })
                }
            }
        });
    }

    loadDelData() {
        this.setState({
            checkData: []//清空table
        }, () => {
            this.loadApplicationList()
        })
    }

    loadApplicationData(e) {
        if (e.keyCode == '13') {
            this.loadApplicationList()
        }
    }

    //检查类，审核成功后，重查列表
    loadRightCardData() {
        this.loadApplicationList()
    }

    //获取申请单列表数据
    loadApplicationRender() {
        var { applicationList } = this.state;
        var applicationListOption = []
        applicationList && applicationList.map((item, index) => {
            applicationListOption.push(
                <Card key={index} onClick={item.mainCode == 'E' ? this.loadTableData.bind(this, item.id, 'list') :
                    (item.mainCode == 'L' ? this.loadCheckTableData.bind(this, item, 'list') : '')}
                    style={{ cursor: 'pointer', marginBottom: 7 }} id={(this.state.selectID == item.id || this.state.selectID == item.ordID) ? 'application-shadow' : null}
                    title={<div style={{ width: '100%', textAlign: 'center', cursor: 'pointer' }}>{item.title}</div>}
                    className="medical-advice-list" extra={(this.state.selectID == item.id || this.state.selectID == item.ordID) ? <div className='application-chooce-box'></div> : null}
                    headStyle={{ background: 'rgba(208, 233, 255, 0.5)', color: 'rgba(0, 0, 0, .7)', fontSize: '12px' }}
                >
                    <Row style={{ padding: '6px', height: '12' }}>
                        <Col span={16}>
                            <div>{this.setMessage('ApplicationFormDate', 'descripts')}{item.orderDate ? item.orderDate : item.ordDate}</div>
                            <div>{this.setMessage('ApplicationFormAmount', 'descripts')}<span style={{ color: '#1999db' }}>{item.price}</span></div>
                            <div>{this.setMessage('ApplicationFormDepartment', 'descripts')}{item.recLocDesc ? item.recLocDesc : item.patLocDesc}</div>
                        </Col>
                        <Col span={8}>
                            <div className={item.appStatusCode == 'P' ? 'charge-status-check' : 'charge-status-uncheck'}
                                style={{ position: 'relative', height: '63px', lineHeight: '63px', textAlign: 'center' }}>
                                {/* <span className="charge-status">{item.appStatus ? item.appStatus : item.statusDesc}</span> */}
                            </div>
                        </Col>
                    </Row>
                </Card>
            )
        })
        return applicationListOption
    }

    delPartData() {
        this.loadTableData(this.state.addID, 'list')
        this.loadApplicationList()
    }

    loadTableData(id, list) {
        var params = {
            params: [{
                appID: id
            }]
        }
        var { dataSource } = this.state;
        if (Util.isEmpty(dataSource)) {
            this.state.dataSource = [],
                this.state.breadcrumb = ''
        }
        this.setState({ radioCode: 'E' })
        setTimeout(() => {
            $http.post('urlDeault', this, {
                code: "03050110",
                data: params,
                success: function (res) {
                    if (res.errorCode == '0') {
                        this.setState({
                            tableData: res.result,
                            tabStatus: true,
                            addID: id,
                            selectID: id,
                            selectList: list
                        })
                    }
                }
            });
        }, 100)
    }

    //将点击的右边申请单列表数据动态加载到对应组件内
    loadCheckTableData(data, list) {
        var { dataSource } = this.state;
        if (Util.isEmpty(dataSource)) {
            this.state.dataSource = [],
                this.state.breadcrumb = ''
        }
        this.setState({ radioCode: data.mainCode, radioList: list, selectID: data.ordID }, () => {
            this.loadSyncTableData(data)
        })
    }

    loadSyncTableData(data) {
        var checkData = []
        checkData.push(data)
        setTimeout(() => {
            this.setState({
                checkData: checkData,
                checkStatus: true,
            })
        }, 100)
    }

    searchBasicData(e) {
        if (e.keyCode == '13') {
            this.loadClassIfication()
        }
    }

    // 隐藏左侧card
    handleHideLeftCard = () => {
        this.setState({ visibleCrad: false })
    }

    // 显示左侧card
    handleShowLeftCard = () => {
        this.setState({ visibleCrad: true })
    }

    //radio切换
    radioOnChange = e => {
        this.setState({
            radioValue: e.target.value,
            radioCode: e.target.code,
            dataSource: [],
            // expandedKeys: []
        }, () => {
            this.loadClassIfication()
        });
    }

    // 树节点内容
    renderTreeNodes() {
        var templateTree = []
        var { classInication } = this.state;
        classInication && classInication.map((item, index) => {
            templateTree.push(<TreeNode title={item.descripts} key={item.CBid} code='' breadcrumb={item.breadcrumb}
                mainCode={item.mainCode} CBid={item.CBid}>
                {this.loadSunTemplate(item.children)}
            </TreeNode>)
        })
        return templateTree
    }

    loadSunTemplate(data) {
        var sunData = []
        data && data.map((item, index) => {
            sunData.push(<TreeNode title={item.descripts} key={item.HBid} code={item.HBid} breadcrumb={item.breadcrumb}
                mainCode={item.mainCode}>
                {this.loadSunTemplate(item.children)}
            </TreeNode>)
        })
        return sunData
    }

    //点击左边树加载数据
    clickTreeNodes(data, code) {
        var dataSource = this.onCheckRef && this.onCheckRef.state.tableData;
        var that = this;
        if (this.state.radioCode !== code.node.props.mainCode) {
            if (!Util.isEmpty(dataSource)) {
                for (var i = 0; i < dataSource.length; i++) {
                    if (!Util.isEmpty(dataSource[i].medID)) {
                        confirm({
                            title: that.setMessage('ApplicationFormsw', 'descripts'),
                            content: that.setMessage('ApplicationFormqqq', 'descripts'),
                            okText: that.state.userData.language == 'EN' ? 'Ok' : '是',
                            cancelText: that.state.userData.language == 'EN' ? 'cancel' : '否',
                            onOk() {
                                that.setState({
                                    nodeID: code.node.props.code,
                                    breadcrumb: code.node.props.breadcrumb,
                                    radioCode: code.node.props.mainCode,
                                    // expandedKeys: data,
                                    CBid: code.node.props.CBid
                                }, () => {
                                    if (that.state.radioCode == 'L') {
                                        that.onSave.saveDoctorAdvice()
                                        that.loadClassificationAdvice()//查询分类医嘱
                                    } else if (that.state.radioCode == 'E') {
                                        that.saveRequest.handleSaveCheckData()
                                        that.loadClassificationAdvice()//查询分类医嘱
                                        that.loadApplicationList()
                                    }
                                    // console.dir(that.onCheckRef)
                                    // this.loadApplicationList()//获取就诊检查申请单列表
                                })
                            },
                            onCancel() {
                                return
                            },
                        })
                    } else {
                        that.setState({
                            nodeID: code.node.props.code,
                            breadcrumb: code.node.props.breadcrumb,
                            radioCode: code.node.props.mainCode,
                            // expandedKeys: data,
                            CBid: code.node.props.CBid
                        }, () => {
                            that.loadClassificationAdvice()//查询分类医嘱
                            // this.loadApplicationList()//获取就诊检查申请单列表
                        })
                    }
                    break;
                }
            } else {
                that.setState({
                    nodeID: code.node.props.code,
                    breadcrumb: code.node.props.breadcrumb,
                    radioCode: code.node.props.mainCode,
                    // expandedKeys: data,
                    CBid: code.node.props.CBid
                }, () => {
                    that.loadClassificationAdvice()//查询分类医嘱
                    // this.loadApplicationList()//获取就诊检查申请单列表
                })
            }
        } else {
            that.setState({
                nodeID: code.node.props.code,
                breadcrumb: code.node.props.breadcrumb,
                radioCode: code.node.props.mainCode,
                // expandedKeys: data,
                CBid: code.node.props.CBid
            }, () => {
                that.loadClassificationAdvice()//查询分类医嘱
                // this.loadApplicationList()//获取就诊检查申请单列表
            })
        }
    }

    onExpand(data) {
        this.setState({ expandedKeys: data })
    }

    //跳转到西药及其他
    goDoctorAdviceStepPage = (num) => {
        var { hashROuter } = this.props;
        hashROuter && hashROuter(num);
    }

    // 本次就诊申请单列表---时间选框
    rangePickerOnChange = (date, dateString) => {
        console.log(date, dateString);
    }

    handleShowQuery = () => {
        this.setState({ showQuery: !this.state.showQuery }, () => {
            let o = document.getElementById("app-right-list");
            let h = o.clientHeight || o.offsetHeight;
            console.log(h)
            this.setState({ appListHeight: h })
        })
    }

    startChange(date) {
        this.setState({
            admDateFrom: date,
        })
    }

    endChange(date) {
        this.setState({
            admDateTo: date,
        })
    }
    //清空自组件传过来的数据
    clearInput() {
        this.setState({
            tableData: [],
            checkData: [],
            tabStatus: false,
            selectID: ''
        }, () => {
            this.loadClassificationAdvice()
        })
    }

    onCheck = (ref) => {
        this.onCheckRef = ref;
    }

    saveRef = (ref) => {
        this.onSave = ref
    }
    saveQueRef = (ref) => {
        this.saveRequest = ref
    }

    loadDisMessage(disBtn) {
        this.setState({
            disBtn: disBtn
        })
    }

    handleChangeBtn(name, e) {
        this.setState({
            [name]: e.target.value
        }, () => {
            if (this.state.defaultBtn == 2) {
                this.goDoctorAdviceStepPage(2)
            } else if (this.state.defaultBtn == 1) {
                this.goDoctorAdviceStepPage(1)
            }
        })
    }

    render() {
        let { visibleCrad, radioValue, showQuery, appListHeight, basicData, radioCode } = this.state;
        //radio数据
        var basicRadioOption = []
        basicData && basicData.map((item, index) => {
            basicRadioOption.push(<Radio key={index} value={item.id} code={item.code}>{item.descripts}</Radio>)
        })
        return (
            <div className="cm-order-save entry-application-form" style={{ background: '#fff' }}>
                <div style={{ height: '6px', background: '#F5F7FE' }}></div>
                <Row style={{ position: 'relative' }}>
                    {!visibleCrad ? <div className='show-card' style={{ float: 'left' }}>
                        <Card
                            className="order-save-hidden-card"
                            style={{
                                width: '20px', background: '#f5f4f4',
                                height: store.getState().tableHeight.y + 117 + 'px'
                                , cursor: 'pointer', paddingTop: 200, textAlign: 'center'
                            }} hoverable={true} onClick={this.handleShowLeftCard}>
                            <div className='change-card-icon-show'><Tooltip title={this.setMessage('ApplicationFormPresentation', 'descripts')}>
                                <Icon type='double-right' style={{ fontSize: '18px' }} /></Tooltip></div>{this.setMessage('ApplicationFormPresentation', 'descripts')}</Card>
                    </div> :
                        <Col span={4} style={{ float: 'left' }}>
                            <Card
                                size="small"
                                title={<span><img src={doctorOrder} style={{ marginRight: 5 }} />{this.setMessage('ApplicationFormApplication', 'descripts')}</span>}
                                headStyle={{ background: '#fff', color: '#1999db' }}
                                className="medical-advice-list"
                            >
                                <div style={{ height: store.getState().tableHeight.y + 110 + 'px', overflow: 'auto' }}>
                                    <div style={{ width: '100%', padding: '0 8px' }}>
                                        <Input
                                            style={{ width: '100%', margin: '6px 0' }}
                                            placeholder={this.setMessage('ApplicationFormenter', 'descripts')}
                                            onChange={Util.commonInputChange.bind(this, 'searchCode')}
                                            onKeyDown={this.searchBasicData.bind(this)}
                                            prefix={<Icon type="search" style={{ color: 'rgba(0,0,0,.25)' }} />}
                                        />
                                    </div>
                                    <div style={{ background: '#F6FCF9', height: '34px', lineHeight: '34px' }}>
                                        <Radio.Group onChange={this.radioOnChange} value={radioValue}>
                                            {basicRadioOption}
                                        </Radio.Group>
                                    </div>
                                    <div className='hide-card' onClick={this.handleHideLeftCard}>
                                        <Tooltip title={this.setMessage('ApplicationFormhide', 'descripts')}>
                                            <Icon type='double-left' style={{ fontSize: '18px' }} />
                                        </Tooltip>
                                    </div>
                                    <Tree
                                        // 是否自动展开父节点
                                        autoExpandParent={true} expandedKeys={this.state.expandedKeys}
                                        onExpand={this.onExpand.bind(this)}
                                        defaultExpandAll={true}
                                        onSelect={this.clickTreeNodes.bind(this)}
                                    >
                                        {this.renderTreeNodes()}
                                    </Tree>
                                </div>
                            </Card>
                        </Col>}
                    <Col
                        span={visibleCrad ? 20 : ''}
                        style={{ borderTop: '1px solid #e8e8e8', paddingLeft: visibleCrad ? '' : '', float: 'right', width: visibleCrad ? '' : '98.8%' }}
                    >
                        <div style={{ paddingLeft: '6px', position: 'relative' }}>
                            <div style={{ position: 'absolute', left: '0', top: '0', width: '6px', background: '#F5F7FE', height: '100%' }}></div>
                            <div style={{ height: store.getState().tableHeight.y + 148 + 'px', overflow: 'auto' }}>
                                <div style={{ height: '36px', lineHeight: '36px', padding: '0 12px' }}>
                                    {this.setMessage('ApplicationFormUncharged', 'descripts')}<span style={{ color: '#1999db', fontSize: '14px', fontWeight: '900', marginRight: '24px' }}>--</span>
                                    {this.setMessage('ApplicationFormTotal', 'descripts')}<span style={{ color: '#1999db', fontSize: '14px', fontWeight: '900' }}>--</span>
                                    <span
                                        className='span-card pointer-span'
                                    >
                                        {this.setMessage('ApplicationFormCard', 'descripts')}
                                    </span>
                                    <div style={{ float: 'right' }}>
                                        {/* <span className="span" onClick={() => this.goDoctorAdviceStepPage(2)}>
                                            {this.setMessage('ApplicationFormMedicine', 'descripts')}
                                        </span>
                                        <span className="span" style={{ margin: '0 12px' }} onClick={() => this.goDoctorAdviceStepPage(1)}>
                                            {this.setMessage('ApplicationFormHerbal', 'descripts')}
                                        </span> */}
                                        <Radio.Group value={this.state.defaultBtn} buttonStyle="solid" onChange={this.handleChangeBtn.bind(this, 'defaultBtn')}>
                                            <Radio.Button value={2}>{this.setMessage('ApplicationFormMedicine', 'descripts')}</Radio.Button>
                                            <Radio.Button value={3}>申请单</Radio.Button>
                                            <Radio.Button value={1}>
                                                {this.setMessage('ApplicationFormHerbal', 'descripts')}</Radio.Button>
                                        </Radio.Group>
                                    </div>
                                </div>
                                <Row>
                                    {/**渲染组件 */}
                                    <Col span={19} style={{ borderBottom: '1px solid #e8e8e8' }}>
                                        {radioCode == 'L' ? (
                                            <InspectionRequest dataSource={this.state.dataSource}
                                                breadcrumb={this.state.breadcrumb}
                                                radioCode={this.state.radioCode}
                                                ref={this.onCheck}
                                                onRef={this.saveQueRef}
                                                loadDelData={this.loadDelData.bind(this)}
                                                tableData={this.state.checkData}
                                                selectID={this.state.selectID}
                                                radioList={this.state.radioList}
                                                disBtn={this.state.disBtn}
                                                clearInput={this.clearInput.bind(this)}
                                                checkStatus={this.state.checkStatus}
                                                searchDataSource={this.loadClassificationAdvice.bind(this)} />
                                        ) : (
                                            <ApplicationCheck dataSource={this.state.dataSource}
                                                searchDataSource={this.loadClassificationAdvice.bind(this)}
                                                radioCode={this.state.radioCode}
                                                ref={this.onCheck}
                                                onRef={this.saveRef}
                                                selectList={this.state.selectList}
                                                DetailData={this.state.DetailData}
                                                selectID={this.state.selectID}
                                                disBtn={this.state.disBtn}
                                                loadRightCardData={this.loadRightCardData.bind(this)}
                                                delPartData={this.delPartData.bind(this)}
                                                tableData={this.state.tableData}
                                                clearInput={this.clearInput.bind(this)}
                                                tabStatus={this.state.tabStatus}
                                                breadcrumb={this.state.breadcrumb} />
                                        )}
                                    </Col>
                                    <Col span={5}>
                                        <Card
                                            size="small"
                                            title={<div style={{ position: 'relative' }}><span style={{ color: 'rgba(102,102,102,1)' }}>
                                                {this.setMessage('ApplicationFormlist', 'descripts')}</span>
                                                <Icon onClick={this.handleShowQuery} type="search" style={{ float: 'right', color: 'rgba(102,102,102,1)', fontSize: '20px', cursor: 'pointer' }} /></div>}
                                            headStyle={{ background: 'linear-gradient(0deg,rgba(238,238,238,0.8) 0%,rgba(238,238,238,0.5) 50%,rgba(238,238,238,0.1) 100%)', color: 'rgba(102,102,102,1)' }}
                                            className="medical-advice-list"
                                        >
                                            <div style={{ height: store.getState().tableHeight.y + 73 + 'px', overflow: 'auto' }}>
                                                <div style={{ display: showQuery ? 'block' : 'none', padding: '8px' }} id="app-right-list">

                                                    <RangeDatePicker format='YYYY-MM-DD' locale={this.state.userData.language}
                                                        // startDate={moment(date).format(dayFormat)} endDate={moment(date).format(dayFormat)}
                                                        startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)} />
                                                    <Row style={{ marginTop: '8px' }}>
                                                        <Col span={20} style={{ paddingRight: '8px' }}>
                                                            <Input placeholder={this.setMessage('ApplicationFormthe', 'descripts')} onChange={Util.commonInputChange.bind(this, 'searchList')}
                                                                onKeyDown={this.loadApplicationData.bind(this)} />
                                                            {/* <RangePicker onChange={this.rangePickerOnChange} /> */}
                                                        </Col>
                                                        <Col span={4} className='application-btn'>
                                                            <Button size='small' onClick={this.loadApplicationList.bind(this)}>{this.setMessage('ApplicationFormsearch', 'descripts')}</Button>
                                                        </Col>
                                                    </Row>
                                                </div>
                                                <div style={{ position: 'relative', height: store.getState().tableHeight.y + 32 - appListHeight + 'px' }} className='application-card-title'>
                                                    <div style={{ display: 'none' }} className="position-center">{this.setMessage('ApplicationFormno', 'descripts')}</div>
                                                    {this.loadApplicationRender()}
                                                </div>
                                            </div>
                                        </Card>
                                    </Col>
                                </Row>
                            </div>
                        </div>
                    </Col>
                </Row>
            </div>
        )
    }
}